<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单ID" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item label="申请时间" style="width: 308px;">
        <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="审核状态" prop="auditState">
        <el-input
          v-model="queryParams.auditState"
          placeholder="请输入审核状态"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:ticket:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:ticket:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:ticket:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:ticket:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ticketList" @selection-change="handleSelectionChange">
      <el-table-column label="用户昵称" align="center" prop="userName" />
      <el-table-column label="抬头类型" align="center" prop="headType" width="130">
        <template #default="scope">
          <span v-if="scope.row.headType === '0'">企业单位</span>
          <span v-if="scope.row.headType === '1'">个人/非企业单位</span>
        </template>
      </el-table-column>
      <el-table-column label="购方名称" align="center" prop="purchaseName" />
      <el-table-column label="购方税号" align="center" prop="purchaseTax" />
      <el-table-column label="公司地址" align="center" prop="companyAddress" width="170"/>
      <el-table-column label="公司电话" align="center" prop="companyPhone" />
      <el-table-column label="开户行" align="center" prop="openBank" />
      <el-table-column label="开户行账号" align="center" prop="openAccount" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="开票总金额" align="center" prop="totalAmount" >
        <template #default="scope">
          <span>{{ parseFloat(scope.row.totalAmount).toFixed(2) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="申请时间" align="center" prop="applicationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applicationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="auditState" >
        <template #default="scope">
          <el-tag v-if="scope.row.auditState === '0'" type="info">待开票</el-tag>
          <el-tag v-if="scope.row.auditState === '1'" type="success">成功</el-tag>
          <el-tag v-if="scope.row.auditState === '2'" type="danger">失败</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width"  fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" v-if="scope.row.auditState == 0" @click="handleUpdate(scope.row),isShow(true)"

                     v-hasPermi="['system:ticket:edit']">开票
          </el-button>
          <el-button link type="primary" icon="View" v-if="scope.row.auditState == 1" @click="handleUpdate(scope.row),isShow(false)"
                     v-hasPermi="['system:ticket:view']">查看
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:ticket:remove']">删除
          </el-button>
        </template>
      </el-table-column>


    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改开票申请对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ticketRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户昵称" prop="userName">
          <el-input disabled v-model="form.userName" placeholder="请输入用户昵称" clearable />
        </el-form-item>
        <el-form-item label="抬头类型" prop="headType">
          <el-input disabled v-model="form.headType" placeholder="请输入抬头类型" clearable />
        </el-form-item>
        <el-form-item label="购方名称" prop="purchaseName">
          <el-input disabled v-model="form.purchaseName" placeholder="请输入购方名称" clearable />
        </el-form-item>
        <el-form-item label="购方税号" prop="purchaseTax">
          <el-input disabled v-model="form.purchaseTax" placeholder="请输入购方税号" clearable />
        </el-form-item>
        <el-form-item label="公司地址" prop="companyAddress">
          <el-input disabled v-model="form.companyAddress" placeholder="请输入公司地址" clearable />
        </el-form-item>
        <el-form-item label="公司电话" prop="companyPhone">
          <el-input disabled v-model="form.companyPhone" placeholder="请输入公司电话" clearable />
        </el-form-item>
        <el-form-item label="开户行" prop="openBank">
          <el-input disabled v-model="form.openBank" placeholder="请输入开户行" clearable />
        </el-form-item>
        <el-form-item label="开户行账号" prop="openAccount">
          <el-input  disabled v-model="form.openAccount" placeholder="请输入开户行账号" clearable />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input disabled v-model="form.remark" placeholder="请输入备注" clearable />
        </el-form-item>
        <el-form-item label="开票总金额" prop="totalAmount">
          <el-input disabled v-model="form.totalAmount" placeholder="请输入开票总金额" clearable />
        </el-form-item>
<!--        <el-form-item label="发票上传" prop="">-->
<!--          <el-image style="width: 100px; height: 80px;" v-if="form.identifyCardPositive"-->
<!--                    :src="form.identifyCardPositive" fit="contain" title="点击查看大图"-->
<!--                    :preview-src-list="[form.identifyCardPositive]" preview-teleported hide-on-click-modal>-->
<!--          </el-image>-->
<!--        </el-form-item>-->


        <el-form-item label="发票上传" prop="ticket">
          <el-upload
              :headers="uploadss.headers"
              class="carouse"
              :action="uploadss.url"
              :show-file-list="false"
              :auto-upload="true"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
          >
            <img class="carouse-img" v-if="form.ticket" :src="form.ticket"/>
            <el-icon v-else class="carouse-plus"><Plus/></el-icon>
          </el-upload>
        </el-form-item>


        <el-form-item label="申请处理" prop="auditState">
          <el-radio-group v-model="form.auditState">
            <el-radio label="1">同意开票</el-radio>
            <el-radio label="2">拒绝开票</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>


      <template #footer>
        <div class="dialog-footer" >
          <el-button type="primary" @click="submitForm" v-if="flag===1">确 定</el-button>
          <el-button @click="cancel" v-if="flag===1">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Ticket">
import { listTicket, getTicket, delTicket, addTicket, updateTicket } from "@/api/system/ticket";

const { proxy } = getCurrentInstance();
const dateRange = ref([]);
const ticketList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//默认为0
const flag = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    applicationDate: null,
    auditState: null,
  },
  rules: {
    orderId: [
      { required: true, message: "订单ID不能为空", trigger: "blur" }
    ],
    applicationId: [
      { required: true, message: "开票申请人ID不能为空", trigger: "blur" }
    ],
    headType: [
      { required: true, message: "抬头类型不能为空", trigger: "change" }
    ],
    purchaseName: [
      { required: true, message: "购方名称不能为空", trigger: "blur" }
    ],
    totalAmount: [
      { required: true, message: "总金额不能为空", trigger: "blur" }
    ],
    auditState: [
      { required: true, message: "审核状态不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询开票申请列表 */
function getList() {
  loading.value = true;
  listTicket(proxy.addDateRange(queryParams.value,dateRange.value)).then(response => {
    ticketList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}


// 表单重置
function reset() {
  form.value = {
    ticketId: null,
    orderId: null,
    applicationId: null,
    headType: null,
    purchaseName: null,
    purchaseTax: null,
    companyAddress: null,
    companyPhone: null,
    openBank: null,
    openAccount: null,
    remark: null,
    totalAmount: null,
    ticket: null,
    applicationDate: null,
    auditState: null,
    dealMan: null
  };
  proxy.resetForm("ticketRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.ticketId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加开票申请";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _ticketId = row.ticketId || ids.value
  getTicket(_ticketId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改开票申请";
  });
}
//是否能继续修改
const isShow = (flagStatus) => {
  if(flagStatus){
     flag.value=1;
  }else{
    flag.value=0;
  }
}
/** 提交按钮 */
function submitForm() {

  proxy.$refs["ticketRef"].validate(valid => {
    if (valid) {
      if (form.value.ticketId != null) {
        updateTicket(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTicket(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ticketIds = row.ticketId || ids.value;
  proxy.$modal.confirm('是否确认删除开票申请编号为"' + _ticketIds + '"的数据项？').then(function() {
    return delTicket(_ticketIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/ticket/export', {
    ...queryParams.value
  }, `ticket_${new Date().getTime()}.xlsx`)
}
//上传成功
function handleSuccess(e){
  if(e.code == 200){
    proxy.$message.success("上传成功");
    form.value.ticket = e.msg
  }else{
    proxy.$message.error("上传失败,请重新上传！");
  }
}

//默认上传之前

function beforeUpload(file) {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg']; // 允许的文件类型
  const isValidType = allowedTypes.includes(file.type);

  if (!isValidType) {
    proxy.$message.error('只能上传 JPG 或 PNG 格式的图片！');
    return false;
  }

  const maxSize = 5 * 1024 * 1024; // 最大文件大小为2MB
  if (file.size > maxSize) {
    proxy.$message.error('文件大小不能超过 2MB！');
    return false;
  }

  return true;
}

function getCookie(name) {
  let cookieArray = document.cookie.split(';'); // 将cookie字符串分割成数组
  for(let i = 0; i < cookieArray.length; i++) {
    let cookie = cookieArray[i];
    // 去除cookie前后的空格
    while (cookie.charAt(0) === ' ') {
      cookie = cookie.substring(1);
    }
    // 检查cookie名称是否匹配
    if (cookie.indexOf(name + '=') === 0) {
      return cookie.substring(name.length + 1, cookie.length);
    }
  }
  return ''; // 如果没有找到指定的cookie，则返回空字符串
}
const uploadss = ref({
  // 设置上传的请求头部
  headers: { Authorization: "headers " + getCookie('Admin-Token') },
  // headers: { Authorization: "Bearer " + getCookie('Admin-Token') },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/uploadOss",
  // 照片地址
  imgUrl: import.meta.env.VITE_APP_BASE_API + "/system/upload/ticket",
});
getList();
</script>
